﻿# coding:utf-8
import url_manager
import html_downloader
import html_parser
import data_outputer
import config_load

#http://www.qiushibaike.com/hot/page/1/
#抓取糗事百科热门段子
#过滤带有图片的段子
#抓取一个段子的发布时间，发布人，段子内容，点赞数
class SpiderMain(object):
    def __init__(self, output_file):
        self.urlm = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = data_outputer.DataOutputer(output_file)
    
    def craw(self, root_url):
        if root_url is None:
            return
        self.urlm.add_new_url(root_url)
        while self.urlm.has_new_url():
            try:
                new_url = self.urlm.get_new_url()
                print 'craw url : %s' %new_url
                content = self.downloader.down_url(new_url)
                #print content
                url_count,page_data = self.parser.parser_page(content)
                #print url_count,page_data
                self.urlm.add_new_urls('10',root_url)
                #print '--come--'
                self.outputer.output(page_data, output_file)
            except Exception, e:
                print e
                print 'craw failed.'
        self.outputer.close()

if __name__ == '__main__':
    config = config_load.ConfigLoad()
    config.load('config.ini')
    root_url = config.get_root_url()
    output_file = config.get_output_file()
    spider_main = SpiderMain(output_file)
    spider_main.craw(root_url)
    
















